package org.mics.core.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mics.cache.redis.RedisHelper;
import org.mics.core.annotation.RLock;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 锁拦截
 * @author mics
 * @date 2022-1-17
 * @version  1.0
 */
@Component
@ConditionalOnProperty(prefix = "cyy.componet.cache",name="type",havingValue = "redis" )
public class RLockInterceptor implements HandlerInterceptor{
	@Resource
	private RedisHelper redisHelper ;
	@Value(value = "${cyy.componet.cache.type}")
	private String cacheType;
	
	/**
	 *  方法中分布式锁校验
	 */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
    	 //如果请求不是后台方法不需要验证token
        if (! (handler instanceof HandlerMethod)) {
        	return true;
        }
        RLock rLock = ((HandlerMethod) handler).getMethodAnnotation(RLock.class);
        if(rLock == null) {
        	return true;
        }
		redisHelper.lock(rLock.value());
		return true;
    }

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		 //如果请求不是后台方法不需要验证token
        if (handler instanceof HandlerMethod) {
            RLock rLock = ((HandlerMethod) handler).getMethodAnnotation(RLock.class);
            if(rLock != null) {
        		redisHelper.unlock(rLock.value());
            }
        }
	}

	
    
    
}
